using Microsoft.EntityFrameworkCore;
using Project_Schedule.Configures;
using Project_Schedule.Domain.Receptionist.com.core.dto;
using Project_Schedule.Domain.Receptionist.com.core.Interface;
using Project_Schedule.Domain.Receptionist.com.core.utils;
using Project_Schedule.Domain.Request;
using Project_Schedule.Model;
using Project_Schedule.Model.Entities;
using Project_Schedule.Model.EntitiesHelper;

namespace Project_Schedule.Domain.Receptionist.com.core.Service;

public class System_RegisterService : ISystemRegister
{
    public async Task<JRequest> Register_Schedule_User(RegisterUser dto)
    {
        try
        {
            if (!System_RegisterTools.RegisterCheckout(dto, out var message))
                throw new Exception(message);
            await using var db = new DataDbContext();
            var isHas = await db.SystemUsers?.FirstOrDefaultAsync(e =>
                e.Account == dto.Account);
            if (isHas is not null) throw new Exception("账户已存在");
            await db.SystemUsers.AddAsync(new System_User
            {
                Account = dto.Account,
                Name = dto.Name,
                Password = RsaEncryptUtil.RSAEncrypt(dto.Password),
                CreateTime = DateTime.Now,
                Post = (Schedule_User_Post_Enum)dto.Post,
                Header = dto.Header,
                Sex = (Schedule_User_Sex_Enum)dto.Sex,
                Phone = dto.Phone,
                Email = dto.Email,
                Status = Schedule_User_State_Enum.On,
                IsUsed = System_Audit_Status_Enum.None,
                ErrorCode = null
            });
            await db.SaveChangesAsync();
            return JRequest.Ok(true);
        }
        catch (Exception exception)
        {
            _logHelper.LogError(exception);
            return JRequest.Ok(false, false, exception.Message);
        }
    }

    private readonly INLogHelper _logHelper;

    public System_RegisterService(INLogHelper logHelper)
    {
        _logHelper = logHelper;
    }
}